package cn.mhome.easy.spring.thrift.client;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class ServiceFactory {
	
	private static Map<String , Object > services = new ConcurrentHashMap<String , Object >();

	/**
	 * 获取service接口代理
	 * @param serviceClass
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getService(Class<?> serviceClass){
		
		String serviceName = serviceClass.getName();
		if(services.get(serviceName) == null){
			synchronized (services) {
				if(services.get(serviceName) == null){
					ProxyFactory<T> factory = new ProxyFactory<T>();
					T obj = null;
					try {
						obj = factory.createProxy(serviceClass);
					} catch (Exception e) {
						e.printStackTrace();
					}
					services.put(serviceName, obj);
				}
			}
			
		}
		
		return (T)services.get(serviceName);
	}
	
	/**
	 * 清空已经保存的服务对象的缓存
	 */
	public static void clearServiceCache(){
		synchronized (services) {
			services.clear();
		}
	}
	
}
